package server.core;

import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * The Database class establishes connections to the desired MySQL database.
 * 
 * @author Clayton Edward Taylor
 */
public class Database {

	private String url = null;
	private Properties properties = null;
	private Connection c = null;
	
	/**
	 * Creates a new Database object that can establish connections to the 
	 * MySQL database at the given URL with the given username and password.
	 * 
	 * @param url      - The URL of the MySQL database
	 * @param user     - The username to connect with
	 * @param password - The password for the given username
	 * @throws           ClassNotFoundException If the JDBC driver is not found
	 * @see              Database
	 */
	public Database(String url, String user, String password) 
			throws ClassNotFoundException {
		
		Class.forName("com.mysql.jdbc.Driver");
		this.url = "jdbc:mysql://" + url;
		this.properties = new Properties();
		this.properties.put("user", user);
		this.properties.put("password", password);
		this.properties.put("characterEncoding", 
				Charset.defaultCharset().displayName());
		this.properties.put("useUnicode", "true");
	}
	
	/**
	 * Gets a Connection to the MySQL database
	 * 
	 * @return A Connection to the MySQL database
	 * @throws SQLException If a database access error occurs
	 * @see    Database
	 */
	public Connection getConnection() throws SQLException {
		
		if ((c == null) || (c.isClosed())) {
			c = DriverManager.getConnection(url, properties);
		}
		return c;
	}
}
